import { wxRequest } from '../../utils/server.js';
const _wxRequest = new wxRequest();
const app = getApp()
Page({
  data: {
    listStatus: false, //宫格为false 列表为ture
    imgUrl: app.globalData.imgUrl,
    hasNextPage: false,
    uploadUrl: wx.getStorageSync('uploadUrl'),
    list: [],
    pageNo: 1,
    keyword: '',
    catId: '',
    braId: '',
    catList: [],
    cartList: [],
    adList: [],
    purchase: '',
    sortType: '',
    totalGoodsCount: 0,
    purchaseList: [{
      id: '',
      text: "全部"
    }, {
      id: 1,
      text: "仅限平台采购"
    }, {
      id: '0',
      text: "商城商品"
    }],
  },
  onLoad: function () {
    this.getlist();
    // this.findAdPicture();
  },

  onHide: function () {
    this.saveShopCartList();
  },


  saveShopCartList () {
    let cartList = wx.getStorageSync('goodsOdrList');
    console.log(cartList)
  },

  onShow: function () {
    this.setData({
      uploadUrl: wx.getStorageSync('uploadUrl'),
    })
    this.getShopCartList();

    //this.getlist();
    this.findAdPicture();

  },

  goPay () {
    let goodsList = wx.getStorageSync('goodsOdrList');
    goodsList.map((item, index) => {
      delete item.id;
      _wxRequest.wxTonkenAjax({
        url: app.globalData.apiUrl + '/odr/protected/shoppingCart/add',
        method: 'post',
        data: item
      }, (res) => {
        if (index == goodsList.length - 1) {
          wx.navigateTo({
            url: '/pages/menber/purchase/index',
          })
        }
      })

    })
  },

  //加入购物车
  addCart: function (e) {
    let checkItem = e.currentTarget.dataset.item;
    let id = e.currentTarget.dataset.id;
    let cartList = this.data.cartList || []
    let qty = e.detail.x ? 1 : e.detail; //加入购入车数量
    var list = this.data.list
    list.map(item => {
      if (item.id == id) {
        item.qty = qty
      }
    })


    //更新购物车列表,如果已经存在更新数量，如果不存在新增
    var newArr = JSON.stringify(cartList)
    if (newArr.indexOf(checkItem.id) < 0) {
      checkItem.qty = 1
      checkItem.gdsId = checkItem.id
      cartList.push(checkItem)
      delete checkItem.id;
      _wxRequest.wxTonkenAjax({
        url: app.globalData.apiUrl + '/odr/protected/shoppingCart/add',
        method: 'post',
        data: checkItem
      }, (res) => {
        wx.showToast({
          title: '加入购物车成功',
        })
      })
    } else {
      cartList.map(item => {
        if (item.gdsId == id) {
          item.qty = qty
        }
      })

      //过滤掉小于1
      cartList = cartList.filter(item => item.qty > 0)
      checkItem.gdsId = id
      checkItem.qty = qty || 0
      _wxRequest.wxTonkenAjax({
        url: app.globalData.apiUrl + '/odr/protected/shoppingCart/add',
        method: 'post',
        data: checkItem
      })
    }

    this.setData({
      list: list,
      cartList,
      totalGoodsCount: cartList.length,
    })
    wx.setStorageSync('goodsOdrList', cartList)
  },

  //加入购物车
  addCate: function () {
    var params = {
      gdsId: this.data.id,
      qty: 1,
    }
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/odr/protected/shoppingCart/add',
      method: 'post',
      data: params
    }, (res) => {
      wx.showToast({
        title: '加入购物车成功',
      })
    })
  },

  //查询列表
  getlist: function () {
    var params = {
      keyword: this.data.keyword,
      status: this.data.status,
      pageNo: this.data.pageNo,
      catId: this.data.catId,
      sortType: this.data.sortType,
      status: 1,
      braId: this.data.braId
    }
    if (this.data.purchase != '') {
      params.purchase = this.data.purchase
    }
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/gdsMgt/findList',
      method: 'POST',
      data: params
    }, (res) => {
      let list = res.list;
      if (this.data.pageNo !== 1) {
        list = this.data.list.concat(list);
      }

      this.setData({
        list: list,
        pageNo: res.page.pageNo,
        hasNextPage: res.page.hasNextPage,
      });

    })
  },

  //获取购物车列表
  getShopCartList () {
    if (!app.globalData.permissions['shopping:list']) {
      return;
    }
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/odr/protected/shoppingCart/list',
      method: 'POST',
      data: {}
    }, (res) => {
      let list = this.data.list;
      list.map(item => {
        if (res.list.length > 0) {
          res.list.map(cartListItem => {
            if (item.id === cartListItem.gdsId) {
              item.qty = cartListItem.qty
            }
          })
        } else {
          item.qty = 0;
        }
      })
      this.setData({
        totalGoodsCount: res.list.length,
        list,
        cartList: res.list
      })
      wx.setStorageSync('goodsOdrList', res.list)
    })
  },

  //下拉刷新
  onPullDownRefresh: function () {
    this.refreshData();
    wx.stopPullDownRefresh()
  },

  refreshData: function () {
    this.setData({
      pageNo: 1
    })
    this.getlist();
    this.getShopCartList();
  },

  //触底时，加载更多
  onReachBottom: function () {
    if (this.data.hasNextPage) {
      this.setData({
        pageNo: this.data.pageNo + 1
      });
      this.getlist();
    }
  },

  //搜索关键词
  seachInputConfirm: function (e) {
    this.setData({
      pageNo: 1,
      keyword: e.detail.value
    })
    this.getlist();
  },

  seachBtn: function () {
    this.setData({
      pageNo: 1,
      keyword: this.data.keyword
    })
    this.getlist();
  },

  seachInputVal: function (e) {
    var inputval = e.detail.value;
    console.log(e)
    this.setData({
      keyword: inputval
    })
  },

  //清空
  clearInput: function () {
    this.setData({
      keyword: ''
    })
    this.getlist();
  },



  //跳转详情页
  toGoodsDetail (e) {
    if (e.mark.stepperMark == undefined) {
      var id = e.currentTarget.dataset.id
      console.log(e)
      wx.navigateTo({
        url: '/pages/good/detail/index?id=' + id,
      })
    }

  },


  handleFilt: function (e) {
    var sortType = e.currentTarget.dataset.type;
    this.setData({
      sortType
    })
    this.getlist()
  },

  //价格筛选
  handlePice () {
    var sortType = this.data.sortType;
    if (sortType == 4) {
      sortType = 5
    } else {
      sortType = 4
    }
    console.log(sortType, 'sortType')
    this.setData({
      sortType
    })
    this.getlist()
  },


  //********************筛选更多********************
  popupRight: function () {
    this.setData({
      showPopup: true
    })
    this.getCat()
  },

  popupCancel: function () {
    this.setData({
      showPopup: false
    })
  },

  popupConfirm: function () {
    this.getlist();
    this.popupCancel();
  },

  //选择状态
  checkpurchase: function (e) {
    var purchase = e.currentTarget.dataset.id || ''
    console.log(purchase, 'status')
    this.setData({
      purchase
    })
  },

  //选择分类
  handleCatItem: function (e) {
    var code = e.currentTarget.dataset.id;
    this.setData({
      catId: code,
    })
    this.getbrand()
  },

  handlebrand: function (e) {
    var code = e.currentTarget.dataset.id;
    this.setData({
      braId: code,
    })
  },
  //********************筛选更多end********************



  getCat: function () {
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + "/gds/goods/findGoodsCat",
      method: 'POST',
      data: {}
    }, (res) => {
      console.log(res, '分类')
      this.setData({
        catList: res.list
      })
      this.getbrand()
    })
  },

  //品牌
  getbrand: function () {
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + "/gds/brand/find",
      method: 'POST',
      data: {
        catId: this.data.catId
      }
    }, (res) => {
      console.log(res, '品牌')
      const userInfo = wx.getStorageSync('userInfo')
      const list = res.list.filter(e =>e.supId == userInfo.orgId)
      this.setData({
        brandList: list
      })
    })
  },

  handletype () {
    this.setData({
      listStatus: !this.data.listStatus
    })
  },


  //查询广告
  findAdPicture: function () {
    _wxRequest.wxTonkenAjax({
      // url: app.globalData.apiUrl + '/sys/ad/findAdPicture',
      url: app.globalData.apiUrl + '/sys/protected/ad/findAdPictureByUser',
      method: 'POST',
      data: {
        typeId: 1,
        keyword: this.data.keyword,
        orgType: wx.getStorageSync('userInfo').orgType
      }
    }, (res) => {
      let adList = res.list;
      this.setData({
        adList
      })
    })
  },


})